﻿using Leo.Blog.Common.JsonHelper;
using Leo.Blog.ViewModel;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Web;
using System.Web.Mvc;

namespace Leo.Blog.Controllers
{
    public class TestUploadController : BaseController
    {
        // GET: TestUpload
        [HttpGet]
        public ActionResult Index()
        {
            ViewBag.Test = "test";
            return View();
        }
        /// <summary>
        /// 配置所有文件的上传地址
        /// </summary>
        /// <param name="uploadAddressId"></param>
        /// <returns></returns>
        public UploadAddress GetUploadAddress(int key)
        {
            List<UploadAddress> listAddress = new List<UploadAddress>();
            listAddress.Add(new UploadAddress
            {
                Key = 1,
                isContainUserId = false,
                AllFolder = new List<string> { "Upload", "Test" }
            });



            UploadAddress address = listAddress.Where(m => m.Key == key).FirstOrDefault();
            if (address == null)
            {
                return new UploadAddress
                {
                    Key = 0,//默认地址
                    isContainUserId = false,
                    AllFolder = new List<string> { "Upload", "TempFolder" }
                };
            }
            return address;
        }
        /// <summary>
        /// 可以处理上传，上传导入的情况
        /// </summary>
        /// <param name="file"></param>
        /// <param name="addressKey"></param>
        /// <param name="callBack">格式如“Controller/Action”</param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult UpLoadProcess(HttpPostedFileBase file, int addressKey, string callBack = "")
        {
            //获取上传地址，addressKey必须要传
            UploadAddress address = GetUploadAddress(addressKey);
            string rootPath = System.Configuration.ConfigurationManager.AppSettings["UploadFloder"] ?? "C:\\UploadFloder\\";
            string filePathName = string.Empty;

            string localPath = string.Empty, virPath = string.Empty;
            if (address.isContainUserId)
            {
                localPath = Path.Combine(rootPath, this.UserAccount, string.Join("/", address.AllFolder));
                virPath = Path.Combine(this.UserAccount, string.Join("/", address.AllFolder));
            }
            else
            {
                localPath = Path.Combine(rootPath, string.Join("/", address.AllFolder));
                virPath = Path.Combine(string.Join("/", address.AllFolder));
            }
            if (file == null)
            {
                ResCode resCode = new ResCode("0", "上传文件不存在");
                return Json(resCode);
            }
            HttpPostedFileBase erveyfile = file;
            string ext = Path.GetExtension(erveyfile.FileName);
            filePathName = Guid.NewGuid().ToString("N") + ext;
            if (!System.IO.Directory.Exists(localPath))
            {
                System.IO.Directory.CreateDirectory(localPath);
            }
            string path = Path.Combine(localPath, filePathName);
            erveyfile.SaveAs(path);
            string callBackErrorDesc=string.Empty;
            if (!string.IsNullOrEmpty(callBack))
            {
                ResCode callBackCode=CallBackHandler(callBack, path);
                //上传统一处理0：出错，显示Description信息，1上传OK
                if (callBackCode.CodeId.Equals("0"))
                    {//出错返回错误描述
                        callBackErrorDesc = callBackCode.Description;
                    }
            }
            string filePath = virPath + "/" + filePathName;
            var rtnObj = new {
                FilePath=filePath,
                ErrorDesc=callBackErrorDesc
            };
            return Json(rtnObj);
        }
        public ResCode CallBackHandler(string path, string filePath)
        {
            if (path.Contains("/"))
            {
                string[] tempStr = path.Split('/');
                //取得当前方法命名空间
                //System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Namespace
                //命名空间可以自动获取
                string controller = "Leo.Blog.Controllers." + tempStr[0] + "Controller",
                    action = tempStr[1];
                Type t = Type.GetType(controller);
                var obj= Activator.CreateInstance(t);
                MethodInfo mi = t.GetMethod(action);
                try
                {
                    //如果执行的是静态方法，不需要创建对象，
                    //如果执行的是非静态方法，需要var obj= Activator.CreateInstance(t);new一个对象
                    var rtnObj = mi.Invoke(obj, new object[] { filePath });
                    ResCode resCode = JsonHelper.DeserializeJsonToObject<ResCode>(rtnObj.ToString());
                    return resCode;
                }
                catch (Exception ex) {
                    ResCode resCode = new ResCode("0","系统出现异常："+ex.ToString());
                    return resCode;
                }
            }
            return new ResCode("0", "传递callBack参数错误");
        }
        /// <summary>
        /// 测试BootstrapFileInput组件
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public ActionResult BootstrapFileInput()
        {
            return View();
        }
    }
    /// <summary>
    /// 配置上传地址专用类
    /// 生成格式为/UserId/AllFolder[0]/AllFolder[1]/AllFolder[2...n]/...
    /// 或/AllFolder[0]/AllFolder[1]/AllFolder[2...n]/...
    /// </summary>
    public class UploadAddress
    {
        /// <summary>
        /// 上传地址配置的Key值，需要唯一
        /// </summary>
        public int Key { get; set; }
        /// <summary>
        /// 是否需要包含UserId
        /// </summary>
        public bool isContainUserId { get; set; }
        /// <summary>
        /// 第1~n个文件夹名字
        /// </summary>
        public List<string> AllFolder { get; set; }
    }
}
